package com.dianrui.fmi.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.dianrui.fmi.R;
import com.dianrui.fmi.event.RfreshUserImg;
import com.dianrui.fmi.util.MyUtil;
import com.dianrui.fmi.util.NoDoubleClickUtils;
import com.dianrui.fmi.util.OkHttpUtils;
import com.dianrui.fmi.util.SharedUtil;
import com.dianrui.fmi.util.StringUtils;
import com.dianrui.fmi.util.ToastUtil;
import com.dianrui.fmi.util.Url;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {
    private ProgressDialog mProgressDialog;

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.clause_choose)
    CheckBox clauseChoose;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.login_mobile)
    EditText loginMobile;
    @BindView(R.id.login_password)
    EditText loginPassword;
    @BindView(R.id.login_btn)
    Button loginBtn;


    @Override
    public int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        if (!StringUtils.isEmpty(spUtils.getString("member_id"))) {
            JumpActivitys(MainActivity.class);
            finish();
        }
        checkWirtePerssions();
        title.setText(getString(R.string.login_txt));
        back.setVisibility(View.GONE);
        mProgressDialog = new ProgressDialog(LoginActivity.this);
        loginMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                if (loginMobile.length()>0 && loginPassword.length()>0 && clauseChoose.isChecked()) {
                    loginBtn.setBackgroundResource(R.drawable.login_orange_shape);
                }else {
                    loginBtn.setBackgroundResource(R.drawable.gray_shape);
                }
            }
        });

        loginPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                if (loginMobile.length()>0 && loginPassword.length()>0 && clauseChoose.isChecked()) {
                    loginBtn.setBackgroundResource(R.drawable.login_orange_shape);
                }else {
                    loginBtn.setBackgroundResource(R.drawable.gray_shape);
                }
            }
        });
        clauseChoose.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (loginMobile.length()>0 && loginPassword.length()>0 && clauseChoose.isChecked()) {
                        loginBtn.setBackgroundResource(R.drawable.login_orange_shape);
                    }else {
                        loginBtn.setBackgroundResource(R.drawable.gray_shape);
                    }
                }else {
                    loginBtn.setBackgroundResource(R.drawable.gray_shape);
                }
            }
        });
    }

    private void checkWirtePerssions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
            }
        }
    }


    @OnClick({R.id.login_btn,R.id.forget_pwd,R.id.user_protocol})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_btn:
                if (!NoDoubleClickUtils.isDoubleClick()) {
                  if (StringUtils.isEmpty(loginMobile.getText().toString())) {
                        ToastUtil.showToast(getString(R.string.please_input_your_email));
                    } else if (StringUtils.isEmpty(loginPassword.getText().toString())) {
                        ToastUtil.showToast(getString(R.string.login_txt8));
                    } else if (!clauseChoose.isChecked()) {
                      ToastUtil.showToast("Please agree terms");
                  } else {
                        startLogin();
                    }
                }
                break;

            case R.id.forget_pwd:
                JumpActivitys(ForgetPasswordActivity.class);
                break;

            case R.id.user_protocol:
                startActivity(new Intent(LoginActivity.this, WebviewActivity.class).putExtra("explainId","1"));

                break;


            default:
                break;
        }
    }

    private void startLogin() {
        mProgressDialog.setMessage(getString(R.string.logining));
        mProgressDialog.show();
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("account", loginMobile.getText().toString().trim());
        jsonObject.addProperty("verify_code", loginPassword.getText().toString().trim());
        jsonObject.addProperty("device_number", MyUtil.getUniqueId(LoginActivity.this));//设备号
        jsonObject.addProperty("app_type", "1");//设备类型
        jsonObject.addProperty("app_version", MyUtil.getAppInfo(LoginActivity.this));
        jsonObject.addProperty("device_type", MyUtil.getSystemBARND() + "  " + MyUtil.getSystemModel());
        OkHttpUtils.getInstance().postRequests(Url.LOGIN, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject && !isFinishing()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                mProgressDialog.dismiss();
                                spUtils.put("member_id", jsonObject.optJSONObject("data").optString("member_id"));//用户ID，非常重要，必须获取
                                spUtils.put("account", jsonObject.optJSONObject("data").optString("account"));//账户
                                spUtils.put("email", jsonObject.optJSONObject("data").optString("email"));//电子邮件
                                spUtils.put("mobile", jsonObject.optJSONObject("data").optString("mobile"));//手机
                                spUtils.put("nickname", jsonObject.optJSONObject("data").optString("nickname"));
                                spUtils.put("name", jsonObject.optJSONObject("data").optString("name"));
                                spUtils.put("card", jsonObject.optJSONObject("data").optString("card"));
                                spUtils.put("face", jsonObject.optJSONObject("data").optString("face"));
                                spUtils.put("introduce", jsonObject.optJSONObject("data").optString("introduce"));
                                spUtils.put("state", jsonObject.optJSONObject("data").optString("state"));
                                spUtils.put("alias", jsonObject.optJSONObject("data").optString("alias"));
                                SharedUtil.setToken(jsonObject.optJSONObject("data").optString("token"));
                                SharedUtil.setMemberToken(jsonObject.optJSONObject("data").optString("member_token"));
                                EventBus.getDefault().post(new RfreshUserImg());
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));//跳主页

                                switch (jsonObject.optJSONObject("data").optString("state")) {//判断登录状态
                                    case "0":
                                        JumpActivitys(MainActivity.class);
                                        finish();
                                        break;
                                    case "1":
                                        JumpActivitys(MainActivity.class);
                                        finish();
                                        break;
                                    default:
                                        break;
                                }
                            } else {
                                mProgressDialog.dismiss();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    mProgressDialog.dismiss();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

}
